<?php
/**
 * 支付调取
 * @author  wyb <[<email address>]>
 */

namespace Api\Controller;

class PayController extends BaseController {

	public function index() {
		$data = I('get.');
		$pay_open = '';
		if( !isset( $data['pay_type'] ) || !$data['pay_type'] || !in_array( $data['pay_type'] , array('weixin','alipay'))) $this->error( '请选择支付方式' );

		//如果是微信支付 则取出code
		if( $data['pay_type'] == 'weixin' ) {
			$pay_open = $data['openid'];
			unset( $data['openid'] );
		}

		//去掉微信类型
		$pay_type = $data['pay_type'];
		unset( $data['pay_type'] );

		if( \Api\Server\PaymentServer::init()->aignCheck( $data ) === false ) {
			$this->error( '签名认证失败' );
		}
		//判断是否是微信支付 
		if( $pay_type == 'weixin' ) {
			//如果没有code 则需要跳转获得
			if( !$pay_open ) {
	            //跳转微信获取code值,去登陆
	            header( 'Location:http://w3.newbeemall.com/zt_forward/authorize.php?url=' . urlencode( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) );
	            exit;
        	}
		}

		$order_info = $this->_orderInfo( $data['id'] );
		if( $order_info['state'] > 0 ) {
			$this->error( '订单已支付，请勿重复支付' , $order_info['return_url'] );
		}

		//获得配置
		$config = D('Common/PaymentConfig')->getSettingConfig( $data['id'] , $pay_type );
		if( $config === false ) {
			$this->error( '支付不存在！' );
		}
		//记录open_id入数据库
		if( $pay_open ) {
			M('order')->where(array('id' => $data['id']))->save(array('openid' => $pay_open));
		}

		$object_name = '\\Api\\Extend\\Payment\\' . ucfirst( $pay_type ); //组合空间命名
		$object = new $object_name( $config );
		$order_info = array_merge( ( $order_info ? $order_info : array() ) , array('openid' => $pay_open));
		$order_info['pay_body'] = '外部订单产品支付';
		$object->pay_mobile( $order_info );
	}

	/**
	 * 支付回调
	 */
	public function notify() {
		$data = I('post.') ? I('post.') : exit();
		//调取空间扩展
		$payment = $data['payment'];
		unset( $data['payment'] );
		$out_trade_no = explode('_' , $data['out_trade_no']);
		$order_info = M('order')->where(array('ref' => $out_trade_no[0]))->find();
		if( !$order_info ) $this->error( '订单不存在' );
		$config = D('Common/PaymentConfig')->getSettingConfig($order_info['id'] , $payment);
		if( $config === false ) exit;
		$object_name = '\\Api\\Extend\\Payment\\' . ucfirst( $payment ); //组合空间命名
		$object = new $object_name( $config );
		$result = $object->notify( $data );
		//验证成功
		if( $result['status'] == 'success' ) {
			$order_info = M('order')->where(array('ref' => $result['order_sn'] , 'state' => 0))->find();
			if( !$order_info ) exit(json_encode(array('return_url' => $order_info['return_url'] , 'status' => 'error' , 'msg' => '订单不存在')));
			if( $order_info['amount_total'] - $order_info['delivery_fee'] != $result['total_fee'] ) exit(json_encode(array('return_url' => $order_info['return_url'] , 'status' => 'error' , 'msg' => '订单金额不对')));

			M('order')->save(array('state' => 1 ,'id' => $order_info['id'])); //修改订单支付状态
			//增加支付信息
			M('order_payment')->add(array('order_id' => $order_info['id'],'ref' => $order_info['ref'], 'payamount' => $result['total_fee'],'payment_no' => $result['payment_no'],'create_time' => date('Y-m-d H:i:s') , 'payment_account' => $payment));
			//回调支付方式服务器
			if( $order_info['notify_url'] ) {
				$this->send( array(
					'out_trade_no' => $order_info['ref'], //订单号
					'total_fee' => $result['total_fee'], //支付金额
					'payment' => $payment, //支付方式
					'payment_no' => $result['payment_no'], //第三方支付单号
					'pay_state' => 'success', //支付状态
					'time_end' => date('YmdHis')
				), $order_info);
			}
			if( $payment == 'alipay') {
				exit(json_encode(array('url' => $order_info['return_url'] , 'status' => 'success' , 'msg' => '支付成功')));
			}
		}
	}

	/**
	 * 获得订单数据
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	private function _orderInfo( $id ) {
		$order_data = M('order')->where(array('id' => $id))->field('amount_total,delivery_fee,ref,return_url')->find();
		if( $order_data ) {
			return array( 'amount_total' => $order_data['amount_total'] - $order_data['delivery_fee'] , 'ref' => $order_data['ref'] , 'return_url' => $order_data['return_url'] );
		}
	}

	/**
	 * 发送推送请求
	 */
	private function send( $data , $order_info ) {
		$customer = M('customer')->where(array('code' => $order_info['channel_code']))->find();
		if( !$customer ) return;
		$data['app_id'] = $customer['id'];
		$data['sgin'] = \Api\Server\TrilateralCheckServer::init()->aign( $data , $customer['key'] );
		$result = \Api\Server\HttpServer::init()->send( $order_info['notify_url'] , $data );
		extract( $result );
		//成功推送至客户服务器
		if( $status['http_code'] >= 200 && $status['http_code'] < 300  && $result ) {
			$result = strtolower( trim( $result ) );
			//客户端处理成功
			if( $result == 'success' ) {
				D('Common/OrderPaySend')->saveOrderSendInfo($order_info['id'] , 1);
			} else {
				D('Common/OrderPaySend')->saveOrderSendInfo($order_info['id'] , 2 , '对方服务器业务处理失败，返回“error”。');
			}
		} else {
			D('Common/OrderPaySend')->saveOrderSendInfo($order_info['id'] , 3);
		}
	}



}